<?php
// 应用公共函数
/**
 * 系统邮件发送函数
 * @param string $tomail 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author static7 <static7@qq.com>
 */
function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {
    $mail = new \PHPMailer();           //实例化PHPMailer对象
    $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl';          // 使用安全协议
    $mail->Host = "smtp.sina.com"; // SMTP 服务器
    $mail->Port = 465;                  // SMTP服务器的端口号
    $mail->Username = "pangpython@sina.com";    // SMTP服务器用户名
    $mail->Password = "密码";     // SMTP服务器密码
    $mail->SetFrom('pangpython@sina.com', 'static7');
    $replyEmail = '';                   //留空则为发件人EMAIL
    $replyName = '';                    //回复名称（留空则为发件人名称）
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}
/**
 * 密码加密算法
 * @author lixiaoming
 * @time 2017/11/16
 * @param string $pwd 明文密码
 * @param string $username 用户名
 * @param string $encrypt 随机安全码
 * @return string 32位加密字符串
 */
function getMd5($pwd,$username,$encrypt){
    $username = strtolower($username);
    return md5(md5($pwd).$username.$encrypt);
}

/**
 * 随机产生安全码
 * @param $len int 长度
 * @param $type int 类型 1全部字母数字  2数字  3小写字母  4大写字母
 * @return string
 */
function getCode($len,$type=1){
    $code = '';
    switch($type){
        case 1:
            $str = 'abcdefghijklmnopqrstuvwxyz0123456789';
            break;
        case 2:
            $str = '0123456789';
            break;
        case 3:
            $str = 'abcdefghijklmnopqrstuvwxyz';
            break;
        case 4:
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        case 5:
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            break;
        default:
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    }
    for($i=0;$i<$len;$i++){
        $code .= $str[mt_rand(0,mb_strlen($str,'utf-8') -1 )] ;
    }
    return $code;
}

/**
 * 获取真实IP
 * @return array|false|string
 */
function get_ip() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else
        if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else
            if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                $ip = getenv("REMOTE_ADDR");
            else
                if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                    $ip = $_SERVER['REMOTE_ADDR'];
                else
                    $ip = "unknown";
    return ($ip);
}


/**
 * Excel表格获取
 * @param $PHPReader PHPExcel对象
 * @param $file_path 文件名
 * @return array
 */
function excel_import($PHPReader,$file_path){
    $Excel = $PHPReader->load($file_path);
    $sheet = $Excel->getSheet(0);           //选择第几个表
    $Column = $sheet->getHighestColumn();   //获取总列数
    $Row = $sheet->getHighestRow();         //获取总行数

    $data = array();                        //用于保存Excel中的数据
    for($i=1;$i<=$Row;$i++){
        //循环获取表中的数据，$i表示当前行,索引值从0开始
        for($j='A';$j<=$Column;$j++){       //从哪列开始，A表示第一列
            $address=$j.$i;//数据坐标
            $data[$i-1][$j]=trim((string)$sheet->getCell($address)->getValue());//读取到的数据，保存到数组$arr中
        }
    }
    return $data;
}

/**
 * 生成username账号
 */
function createUsername(){
    $str = getCode(2,3);//小写字母字符串(两位)
    $str .= msectime();//毫秒时间戳
    return $str;
}

/**
 * 生成默认密码123456
 * @param string $username
 * @return ['encrypt','password'] 加密字段跟md5密码
 */
function createPwd($username=''){
    if(!empty($username)){
        $username = strval($username);
        $pwd = '12345678';
        $encrypt = getCode(6,3);
        return ['encrypt'=>$encrypt,'password'=>getMd5($pwd,$username,$encrypt)];
    }else{
        return false;
    }
}

/**
 * 获取毫秒时间戳
 */
function msectime() {
    list($msec, $sec) = explode(' ', microtime());
    $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

/**
 * 把数组元素为null的剔除,最多支持三维
 * @param array $arr
 */
function eliminateArrNull($arr=[]){
    foreach ($arr as $k=>$v){
        if(is_array($v)){
            foreach ($v as $kk=>$vv){
                if(is_array($vv)){
                    foreach ($vv as $kkk=>$vvv){
                        if($vvv === null) unset($arr[$k][$kk][$kkk]);
                    }
                }else{
                    if($vv === null) unset($arr[$k][$kk]);
                }
            }
        }else{
            if($v === null) unset($arr[$k]);
        }
    }
    return $arr;
}

/**
 * 查询一个数组（一维或多维）是否存在某字符串,返回对应id值
 * @param $str varchar 字符串
 * @param $array array()  数组
 * @return 返回匹配到的值对应的id值
 * */
function deep_in_array($str, $array) {
    $str = trim(str_replace(array("\r\n", "\r", "\n"), "",$str));
    foreach($array as $k=>$item) {
        if(!is_array($item)) {//一维数组
            if ($item == $str) {
                return $k;//返回key
            } else {
                //跳出循环
                continue;
            }
        }
        if(in_array($str, $item)) {//多维数组
            return $item['id'];
        } else if(deep_in_array($str, $item)) {
            return $item['id'];
        }
    }
    unset($array);
    return false;
}

/**
 * 把字符串格式为：1,2,3,a1,bb3,3a 这类的不符合int类型的剔除后返回
 * @param string $str
 * @return strint 1,2,3,3
 */
function strMtions($str=''){
    if(!empty($str)){
        $arr = explode(',',$str);
        $newarr = [];
        foreach ($arr as $v){
            $newarr[] = intval($v);
        }
        return implode(',',array_filter($newarr));
    }
    return '';
}
/**
 * 把字符串格式为：1+2+3+a1+bb3+3a 这类的不符合int类型的剔除后返回
 * @param string $str
 * @return strint 1,2,3,3
 */
function strAddPlus($str=''){
    if(!empty($str)){
        $arr = explode('+',$str);
        $newarr = [];
        foreach ($arr as $v){
            $newarr[] = intval($v);
        }
        return implode('+',array_filter($newarr));
    }
    return '';
}
/*
 * $data array
 * $pId 父级
 * $lev 基类
 */
function getTree($data,$pId,$lev)
{
    $tree = array();
    foreach($data as $k => $v)
    {
        if($v['pid'] == $pId)
        {
            $v['lev'] = $lev;
            $v['cate_ParentId'] = getTree($data, $v['type_id'],$lev+1);
            $tree[] = $v;
            unset($data[$k]);
        }
    }
    return $tree;
}

/**
 * 把年份补全日期
 * @param string $str
 * @return string 2018-01-01
 */
function compYear($str=''){
    $dates = '';
    if(!empty($str) && strlen($str) == 4){
        $dates = $str.'-01-01';
    }
    return $dates;
}

/**
 * Excel表得到的日期数值转换为时间戳
 * @param int $num 时间数值
 * @return int(10) 时间戳
 */
function verDates($num=0){
    if(!empty($num)){
        $d = 25569;
        $num = ($num-$d) * 86400;
    }
    return $num;
}
/*
 * 生成唯一的随机数  uniqid
 * $num 生成的位数 int
 * $hyphen 拼接字符
 * $split 每n个凭接一个字符
 */
 function rand_string($num,$hyphen = '',$split = 4){
     if (empty($hyphen)){
         $hyphen = chr(45);
     }
    mt_srand((double)microtime()*10000);
    $charid =(md5(uniqid(rand(), true)));
    $uuid =substr($charid, 0, $num);
    $uuid = join($hyphen, str_split($uuid, $split));
    return $uuid;
}

/**
 * 获取文件扩展名
 * @param string $file 文件路径
 * @return string txt/jpg
 * */
function getExtension($file=''){
    if($file){
        return pathinfo($file, PATHINFO_EXTENSION);
    }
}

/**
 * 把数组索引转为以id为索引
 * @param array $arr  数组
 * 例子：   array(0=>array('id'=>'1'),1=>array('id'=>'2'))
 * @return array(1=>array('id'=>'1'),2=>array('id'=>'2'))
 * */
function IdKeys($arr){
    if(is_array($arr)){
        $newarr = array();
        foreach ($arr as $k=>$v){
            $newarr[$v['id']] = $v;
        }
        return $newarr;
    }
}

/**
 * 生成订单编号
 * 13位时间戳+11位随机数
 * @return 152325493305339856246252 返回24位编号
 */
function create_ordernum(){
    $str = msectime().getCode(11,2);
    return $str;
}


/**
 * eeo请求方法
 * @param   string  $url    执行的url
 * @param   string  $data   传入的数据
 * @return      string  $content
 */
function eeo_post($url, $data)
{
    $ch = curl_init();
    $timeout = 300;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //构造来路
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $handles = curl_exec($ch);
    $handles = json_decode($handles,true);
    if($handles['error_info']['errno'] == 1){
        $res['code'] = 200;
        $res['msg'] = '成功';
        $res['data'] = isset($handles['data'])?$handles['data']:[];
    }else{
        $res['code'] = $handles['error_info']['errno'];
        $res['msg'] = isset($handles['error_info']['error'])?$handles['error_info']['error']:'未知错误';
        $res['data'] = [];
    }
    unset($handles['error_info'],$handles['data']);
//    if($handles == false){
//        $handles['error'] = curl_error($ch);//获取错误
//    }
    curl_close($ch);
    return $res;
}

/**
 * 根据时间戳计算年龄函数
 * @param  $birthday 出生时间 uninx时间戳
 * @param  date  当前时间
 **/
function birthday($birthday){
//    list($year,$month,$day) = explode("-",$birthday);
    $year_diff = date("Y") - date('Y',$birthday);
    $month_diff = date("m") - date('m',$birthday);
    $day_diff  = date("d") - date('d',$birthday);
    if ($day_diff < 0 || $month_diff < 0) return $year_diff--;
    return $year_diff;
}

/**
 * 权限递归循环取得无限级树
 * @param $arr 处理数组
 * @param int $pid 父级键
 * @return array 返回树
 */
function arrange_tree($arr,$pid=0)
{
    $tree=array();
    foreach ($arr as $item) {
        if ($item['pid'] == $pid){
            $item['children'] = arrange_tree($arr,$item['id']);
            if (empty($item['children'])){
                unset($item['children']);
            }
            $tree[] = $item;
        }
    }
    return $tree;
}

/*
 * 获取星期
 */
function _week($week='',$str=''){
    $week_arr = [
        '日',
        '一',
        '二',
        '三',
        '四',
        '五',
        '六'
    ];
    $str = !empty($str)?$str:'周';

    $str .= isset($week_arr[$week])?$week_arr[$week]:'';
    return $str;
}

//二维数组去重
function array_unset_tt($arr,$key){
    $res = array();
    foreach ($arr as $value) {
        if(isset($res[$value[$key]])){
            unset($value[$key]);
        }else{
            $res[$value[$key]] = $value;
        }
    }
    return $res;
}


/**
 * @param 根据生日计算年龄
 * @return bool|false|int
 *
 */
function getAge($birthday=0){
    $birthday = $birthday?$birthday:0;
    $age = strtotime(date('Y-m-d',$birthday));
    if($age === false){
        return false;
    }
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
    $now = strtotime("now");
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
    $age = $y2 - $y1;
    if((int)($m2.$d2) < (int)($m1.$d1))
        $age -= 1;
    return $age;
}

/**
 * 生成流水号
 * 日期时分秒+10位随机数
 * @return 2018050713575252465235 返回24位编号
 */
function create_orderls(){
    $str = date('YmdHis').getCode(10,2);
    return $str;
}

/**
 * 根据日期转换星期，返回英文
 * @param date 日期，格式：2018-05-05
 */
function weeks_reeng($dates=''){
    $str = '';
    if(!empty($dates)){
        $week = date('w',strtotime($dates));
        $week_arr = [
            'Sunday',
            'Monday',
            'Tuesday',
            'Wednesday',
            'Thursday',
            'Friday',
            'Saturday'
        ];
        $str = isset($week_arr[$week])?$week_arr[$week]:'';
    }
    return $str;
}

/**
 * 生成二维码
 * @param string $url 二维码链接
 * @param int $size 图片大小
 * @param int $margin 白色边距
 * @param int $logo_type 生成带logo的二维码
 */
function create_qrcode($url='',$size=5,$margin=2,$logo_type=0){
    vendor('phpqrcode.phpqrcode');
    ob_end_clean();
    $filename = 'public/qrcodeimg/'.getCode(20,1).'.png';
    $errorCorrectionLevel = 'L';//容错级别
    QRcode::png($url,$filename,$errorCorrectionLevel,$size,$margin);

    switch ($logo_type){
        case 1:
            //网站logo
            $logo = 'public/images/logo.png';
            break;
        case 2:
            //支付宝
            $logo = 'public/images/aplipay.png';
            break;
        case 3:
            //微信
            $logo = 'public/images/wexpay.png';
            break;
        case 4:
            //classin
            $logo = 'public/images/classin.png';
            break;
        default:
            break;
    }
    $QR = false;
    if(!empty($logo)){
        $QR = imagecreatefromstring ( file_get_contents ( $filename ) );
        $logo = imagecreatefromstring ( file_get_contents ( $logo ) );
        $QR_width = imagesx ( $QR );
        $QR_height = imagesy ( $QR );
        $logo_width = imagesx ( $logo );
        $logo_height = imagesy ( $logo );
        $logo_qr_width = $QR_width / 6;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        imagecopyresampled ( $QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height );

        imagepng ( $QR,$filename);//带Logo二维码的文件名
    }
    return $filename;
}

/**
 * 将数据按时间分组
 * @param array $data
 * @return array
 */
function timeGrouping( $data = [] )
{
    $curyear = date('Y');
    $visit_list = [];
    $i=0;
    foreach ($data as $k=>$v) {
        $date = '';
        $stime = '';
        $stime = date('Ymd',$v['set_date']);
        if ($curyear == date('Y', $v['set_date'])) {
            $date = date('m月d日', $v['set_date']);
        } else {
            $date = date('Y年m月d日', $v['set_date']);
        }
        $visit_list[$stime]['dates'] = $date;
        $visit_list[$stime]['time'] = $v['set_date'];
        $visit_list[$stime]['list'][] = $v;
        $i++;
    }
//    return $visit_list;
    $newarr = [];
    foreach ($visit_list as $k=>$v){
        $newarr[] = $v;
    }
    unset($visit_list,$data);
    return $newarr;
}
/*
 * 写入日志
 * $text string 写入的日志
 * $url string 要存放的路劲 当前文件的上一级
 * ./../../../runtime/pay/
 */
	function writeLog($text,$url='./') {
		// $text=iconv("GBK", "UTF-8//IGNORE", $text);
		//$text = characet ( $text );
		file_put_contents ( dirname ( __FILE__ ).DIRECTORY_SEPARATOR."{$url}log.txt", date ( "Y-m-d H:i:s" ) . "  " . $text . "\r\n", FILE_APPEND );
	}


/**
 * 根据日期转换月份，返回英文
 * @param date 日期，格式：2018-05-05
 */
function month_reeng($dates=''){
    $str = '';
    if(!empty($dates)){
        $month = date('n',strtotime($dates));
        $month_arr = [
            'January',
            'February',
            'March',
            'April',
            'May',
            'June',
            'July',
            'August',
            'September',
            'October',
            'November',
            'December'
        ];
        $str = isset($month_arr[$month-1])?$month_arr[$month-1]:'';
    }
    return $str;
}


